package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CancelOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author zhuqiushi
 * @since 2022/09/21 16:35
 */
@Component
@Slf4j
public class CancelUpdateOrderHandler extends AbstractTransHandler{
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CancelOrderContext cancelOrderContext = (CancelOrderContext) context;
        //在这里修改order表
        Order order = new Order();
        order.setOrderId(cancelOrderContext.getOrderId());
        order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
        order.setUpdateTime(new Date());
        int affectRows = orderMapper.updateByPrimaryKeySelective(order);
        if (affectRows < 1) {
            throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), OrderRetCode.DB_EXCEPTION.getMessage());
        }
        Example example = new Example(OrderItem.class);
        example.createCriteria().andEqualTo("orderId", cancelOrderContext.getOrderId());
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        if (orderItems.size()<1) {
            throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), OrderRetCode.DB_EXCEPTION.getMessage());
        }
        cancelOrderContext.setOrderItems(orderItems);
        return true;
    }
}
